package com.dubbo;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * @author caoqianhuan
 * @date 2022/10/11
 * @Description:
 */
public class MyClassLoaderBreakParent extends ClassLoader{
    public static final String ROOT_PATH = "D:\\myyproject\\dubbo-parent\\jvm\\target\\classes\\com\\dubbo\\";
    @Override
    public Class<?> loadClass(String name) {
        String className = ROOT_PATH + name;
        findLoadedClass(className);
        Class class_ = null;
        ClassLoader classLoader = getSystemClassLoader();
        try {
            class_ = classLoader.loadClass(className);
            return class_;
        } catch (ClassNotFoundException e) {
            System.out.println("jdk类加载器找不到要加载的类");
        }
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        try {
            Files.copy(Paths.get(className), byteArrayOutputStream);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        byte[] bytes = byteArrayOutputStream.toByteArray();
        class_ = defineClass(bytes, 0, bytes.length);

        return class_;
    }

    public static void main(String[] args) throws ClassNotFoundException {
        MyClassLoaderBreakParent myClassLoaderBreakParent = new MyClassLoaderBreakParent();
        Class clazz = myClassLoaderBreakParent.loadClass("A.class");
        System.out.println(clazz.getClassLoader());
    }
}
